import hashlib
from app1.models import *
from datetime import datetime
from datetime import date
from datetime import time
import pytz  # UTC时间辅助
import json
import os
from MVonline1 import settings

_TAG = '苟利国家生死以'

# 获取某个字符串的MD5，是加上TAG的MD5
def _getMD5(s:str):
    s += _TAG
    return hashlib.md5(s.encode()).hexdigest()

# 创建或更新用户的token
def create_token(user:User):
    token = Token.objects.filter(user=user).first()
    now = datetime.now(tz=pytz.timezone('UTC'))
    if not token:
        md5 = _getMD5(user.username+user.password+str(now))
        Token.objects.create(userID=md5,user=user,lastTime=now)
        return md5
    else:
        token.lastTime=now   # 自动更新
        token.save()
        return token.userID # 已经存在

# 检查token是否过期, 不过期返回用户,过期删除token，返回False
def check_token(uid:str):
    if not uid:
        return False
    token = Token.objects.filter(userID=uid).first()
    if token:
        dat1 = token.lastTime
        now = datetime.now(tz=pytz.timezone('UTC'))
        if (now-dat1).seconds <= 24*60*60:  #过期时间
            token.lastTime=now   # 自动更新
            token.save()
            return token.user
        else: 
            # 过期,则删除
            token.delete()
    return False

# JSON 格式化时间
class CJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj,  datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj,  date):
            return obj.strftime("%Y-%m-%d")
        elif isinstance(obj,  time):
            return obj.strftime("%H-%M-%S")
        else:
            return json.JSONEncoder.default(self, obj)

# 删除原本资源或者减一
def delete_res(resList:ResList):
    res = resList.res
    resList.delete()
    # 删除引用
    if res.num <= 1:
        _delete_file(res.realPath)
        res.delete()
    else:
        res.num -= 1
        res.save()

# 强制删除文件
def _delete_file(filename):
    while True:
        try:
            if os.path.exists(os.path.join(settings.FILE_PATH, filename)):
                os.remove(os.path.join(settings.FILE_PATH, filename))
            break
        except:
            continue
# 返回用户已经使用的空间大小，单位字节
def get_usedsize(user:User):
    resLists = ResList.objects.filter(user=user)
    userdsize=0
    for item in resLists:
        userdsize += item.res.fileSize
    return userdsize

# 判断用户空间是否充足
def check_size(user:User, newSize):
    usedsie = get_usedsize(user)
    hasSize = user.vip.size * (1024**3)
    if (usedsie + newSize ) > hasSize:
        return False
    else:
        return True




